import { MigrationInterface, QueryRunner, Table, TableColumnOptions, TableIndexOptions } from 'typeorm'
import { consoleLogger } from '@/utils/logger'
import { EUserStatus } from '@/types/common'
import User from '@/models/mysql/User'

// 表格列配置
const tableColumns: TableColumnOptions[] = [
  {
    name: 'id',
    type: 'bigint',
    isPrimary: true,
    isGenerated: true,
    generationStrategy: 'increment',
    unsigned: true,
    comment: '用户ID，主键'
  },
  { name: 'username', type: 'varchar', length: '30', isNullable: false, comment: '用户名' },
  { name: 'crypt_pwd', type: 'varchar', length: '64', isNullable: false, comment: '密码-密文' },
  { name: 'nickname', type: 'varchar', length: '30', isNullable: true, comment: '昵称', default: null },
  { name: 'phone', type: 'char', length: '11', isNullable: false, comment: '手机号', default: '""' },
  { name: 'avatar', type: 'varchar', length: '100', isNullable: true, comment: '头像', default: null },
  {
    name: 'status',
    type: 'enum',
    enum: [`${EUserStatus.DISABLE}`, `${EUserStatus.NORMAL}`],
    isNullable: false,
    comment: '状态：1-正常，0-禁用',
    default: EUserStatus.NORMAL
  },
  { name: 'created_at', type: 'timestamp', isNullable: false, comment: '创建时间', default: 'NOW()' },
  {
    name: 'updated_at',
    type: 'timestamp',
    isNullable: false,
    comment: '更新时间',
    default: 'NOW()',
    onUpdate: 'NOW()'
  },
  { name: 'is_deleted', type: 'boolean', isNullable: false, comment: '是否已删除', default: false }
]

// 索引配置
const indexColumns: TableIndexOptions[] = [
  { name: 'usernameIndex', columnNames: ['username'] },
  { name: 'phoneIndex', columnNames: ['phone'] },
  { name: 'statusIndex', columnNames: ['status'] }
]

export class Users1726120954382 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<boolean> {
    try {
      const userTable = new Table({
        name: 'users',
        engine: 'InnoDB',
        comment: '用户信息表',
        columns: tableColumns,
        indices: indexColumns
      })
      await queryRunner.createTable(userTable, true, true, true)
      const user = new User()
      user.username = 'admin'
      user.password = 'admin'
      user.phone = '18888888888'
      user.status = EUserStatus.NORMAL
      user.nickname = '管理员'
      await queryRunner.manager.save(user)
      consoleLogger.info('创建用户表成功')
      return true
    } catch (e) {
      consoleLogger.error('创建用户表失败', e)
      await this.down(queryRunner)
      return false
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.dropTable('users', true, true, true)
  }
}
